package com.magic.himalaya.presenters;

import androidx.annotation.Nullable;

import com.magic.himalaya.interfaces.IAlbumDetailPresenter;
import com.magic.himalaya.interfaces.IAlbumDetailVIewCallBack;
import com.magic.himalaya.utils.LogUtil;
import com.ximalaya.ting.android.opensdk.constants.DTransferConstants;
import com.ximalaya.ting.android.opensdk.datatrasfer.CommonRequest;
import com.ximalaya.ting.android.opensdk.datatrasfer.IDataCallBack;
import com.ximalaya.ting.android.opensdk.model.album.Album;
import com.ximalaya.ting.android.opensdk.model.track.Track;
import com.ximalaya.ting.android.opensdk.model.track.TrackList;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description:
 * @create: Create by Magic on 2022/1/22.
 */
public class AlbumDetailPresenter implements IAlbumDetailPresenter {
    private static final String TAG = AlbumDetailPresenter.class.getSimpleName();

    private List<IAlbumDetailVIewCallBack> callBackList = new ArrayList<>();

    private static AlbumDetailPresenter albumDetailPresenter = null;

    private Album mTargetAlbum = null;
    private List<Track> mTracks = new ArrayList<>();


    public static AlbumDetailPresenter getInstance() {
        if (albumDetailPresenter == null) {
            synchronized (AlbumDetailPresenter.class) {
                if (albumDetailPresenter == null)
                    albumDetailPresenter = new AlbumDetailPresenter();
            }
        }
        return albumDetailPresenter;
    }

    /**
     * 获得此专辑的所有声音
     *
     * @return
     */
    public List<Track> getTracks() {
        return mTracks;
    }

    /**
     * 设置临时专辑数据
     *
     * @param mTargetAlbum
     */
    public void setmTargetAlbum(Album mTargetAlbum) {
        this.mTargetAlbum = mTargetAlbum;
    }

    /**
     * 获得临时存储的专辑数据
     *
     * @return
     */
    public Album getmTargetAlbum() {
        return mTargetAlbum;
    }

    /**
     * 成功获取数据集时，通知UI渲染数据
     *
     * @param tracks
     */
    private void handlerTracksResult(List<Track> tracks) {
        if (tracks != null) {
            if (tracks.size() == 0) {
                for (IAlbumDetailVIewCallBack callBack : callBackList) {
                    callBack.onTrackEmpty();//数据为空时
                }
            } else {
                for (IAlbumDetailVIewCallBack callBack : callBackList) {
                    callBack.onTrackListLoader(tracks);//调用回调渲染数据
                }
            }
        }
    }

    /**
     * 网络出错时，通知UI渲染网络出错页面
     */
    private void handlerError() {
        if (callBackList != null) {
            for (IAlbumDetailVIewCallBack callBack : callBackList) {
                callBack.onNetworkError();//网络错误时
            }
        }
    }

    /**
     * 请求网络,获取资源
     * 获取指定id专辑下的声音，分页查找:每页查找20条数据
     *
     * @param id
     * @param page
     * @return
     */
    private void getTrackList(long id, int page) {
        Map<String, String> map = new HashMap<String, String>();
        map.put(DTransferConstants.ALBUM_ID, id + "");//填入专辑ID
        map.put(DTransferConstants.SORT, "asc");//排序方式
        map.put(DTransferConstants.PAGE, page + "");//第几页数
        map.put(DTransferConstants.PAGE_SIZE, 20 + "");
        //获取数量默认为20条
        CommonRequest.getTracks(map, new IDataCallBack<TrackList>() {

            //成功请求到资源时
            @Override
            public void onSuccess(@Nullable TrackList trackList) {
                //获得所有的声音集合
                List<Track> tracks = trackList.getTracks();

                if (tracks.size() == 0) {
                    if (mOnTrackListener != null) {
                        mOnTrackListener.toast("没有更多数据了");
                    }
                } else {
                    //将获得的数据添加在页面的声音列表里，如果存在则不重复添加
                    for (Track track : tracks) {
                        if (!mTracks.contains(track)) {
                            mTracks.add(track);
                        }
                    }

//                  mTracks.addAll(tracks);//将获得的数据添加在列表里
                    LogUtil.d(TAG, mTracks.size() + "::::");
                    handlerTracksResult(mTracks);//通知UI渲染数据
                    if (mOnTrackListener != null) {
                        mOnTrackListener.toast(null);
                    }
                    if (mOnMainActivityListener != null) {
                        mOnMainActivityListener.setData(mTracks);
                    }
                }
            }

            //请求失败时
            @Override
            public void onError(int i, String s) {
                handlerError();
                LogUtil.e(TAG, "请求数据出错 ，code——————>" + i + " ，message——————>" + s);
            }
        });
    }
    // ======================= 接口层实现

    /**
     * 用于获取专辑下的声音，此方法用来初始化用，只能加载20条数据
     *
     * @param id
     */
    @Override
    public void getAlbumDetail(long id, int page) {
        mTracks.clear();//清除数据
        getTrackList(id, page);
    }

    /**
     * 下拉刷新
     */
    @Override
    public void pullToRefreshMore() {

    }

    /**
     * 上拉加载更多，将在原有的数据上进行增加
     */
    @Override
    public void loadMore(long id, int page) {
        getTrackList(id, page);
    }

    /**
     * 注册回调UI
     *
     * @param callBack
     */
    @Override
    public void registerViewCallBack(IAlbumDetailVIewCallBack callBack) {
        //防止重复加入
        if (!callBackList.contains(callBack)) {
            callBackList.add(callBack);
        }
    }

    /**
     * 取消注册回调UI
     *
     * @param callBack
     */
    @Override
    public void unRegisterViewCallBack(IAlbumDetailVIewCallBack callBack) {
        //移除callback
        callBackList.remove(callBack);
    }


    //=========================  以下接口回调
    private OnTrackListener mOnTrackListener = null;
    private OnMainActivityListener mOnMainActivityListener = null;

    public void setOnTrackListener(OnTrackListener onTrackListener) {
        mOnTrackListener = onTrackListener;
    }

    public void setOnMainActivityListener(OnMainActivityListener onMainActivityListener) {
        mOnMainActivityListener = onMainActivityListener;
    }

    public interface OnTrackListener {
        void toast(String str);
    }

    public interface OnMainActivityListener{
        void setData(List<Track> trackList);
    }
}
